package cn.com.dragonsoftbravo.utils;

import java.io.ByteArrayOutputStream;

public class StringTransformer {
	/*
	 * transform to hex data from string for all characters(include Chinese)
	 */
	public static String encode(String str) {
		byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	/*
	 * hex charset 
	 */
	private static String hexString = "0123456789ABCDEF";

	/*
	 * transform to string  from hex data for all charaters(include Chinese)
	 */
	public static String decode(String bytes) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(
				bytes.length() / 2);
		for (int i = 0; i < bytes.length(); i += 2)
			baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
					.indexOf(bytes.charAt(i + 1))));
		return new String(baos.toByteArray());
	}
}
